package com.ruoyi.auth.controller;

 import com.alibaba.fastjson.JSON;
import com.ruoyi.auth.form.LoginBody;
import com.ruoyi.auth.form.LoginByEmail;
import com.ruoyi.auth.service.CodeService;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.security.service.TokenService;
import com.ruoyi.shop.api.RemoteShopService;
import com.ruoyi.shop.api.domain.CheDrawal;
import com.ruoyi.shop.api.domain.CheShop;
import com.ruoyi.system.api.domain.SysUser;
import com.ruoyi.system.api.model.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashSet;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName CodeController
 * @Author Jovan HOU
 * @Date 2025年01月06日 19:40
 */
@RestController
public class CodeController extends BaseController
{
    @Autowired
    private CodeService codeService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private RemoteShopService remoteShopService;

    @PostMapping(path = "tocode")
    public AjaxResult sendMailSecurityCode(@RequestBody LoginByEmail loginByEmail) {
        codeService.sendMailCode(loginByEmail.getEmail());
        return success("发送成功");
    }
//    注册验证码发送
@PostMapping("registercode")
public R<?> register(@RequestBody LoginByEmail loginByEmail) {
    if (loginByEmail == null || isNullOrEmpty(loginByEmail.getEmail())) {
        return R.fail("邮箱地址不能为空");
    }

    // 调用远程服务，验证 Email 对应的用户是否存在
    AjaxResult phone = remoteShopService.phone(loginByEmail.getEmail(), null);
    if (phone == null || !phone.isSuccess()) {
        return R.fail("查询远程服务失败");
    }

    Object o = phone.get(AjaxResult.DATA_TAG);

    if (o == null) {
        // 如果没有找到用户，可以认为是注册流程的正常流程
        logger.info("未找到对应的用户数据，继续进行注册流程");
    } else {
        // 如果找到了对应的用户，返回错误提示
        CheShop cheShop = null;
        try {
            cheShop = JSON.parseObject(o.toString(), CheShop.class);
        } catch (Exception e) {
            return R.fail("解析用户信息失败");
        }

        if (cheShop != null) {
            return R.fail("已经存在该用户，请登录");
        }
    }

    // 验证邮箱验证码
    if (isNullOrEmpty(loginByEmail.getCode())) {
        return R.fail("验证码不能为空");
    }

    boolean isVerified = codeService.verify(loginByEmail.getEmail(), loginByEmail.getCode());
    if (!isVerified) {
        return R.fail("验证码无效或已过期");
    }

    // 输出日志
    logger.info("验证通过: {}", loginByEmail.getEmail());

    return R.ok("验证成功");
}

    @PostMapping("security")
    public R<?> verify(@RequestBody LoginByEmail loginByEmail) {
        if (loginByEmail == null || isNullOrEmpty(loginByEmail.getEmail())) {
            return R.fail("邮箱地址不能为空");
        }

        // 调用远程服务，验证 Email 对应的用户是否存在
        AjaxResult phone = remoteShopService.phone(loginByEmail.getEmail(), null);
        Object o = phone.get(AjaxResult.DATA_TAG);

        Object o1 = JSON.toJSON(o);
        CheShop cheShop = JSON.parseObject(o1.toString(), CheShop.class);
        if (cheShop==null){
            return R.fail("未能找到对应的用户信息");
        }

        System.out.println("用户信息: " + cheShop);

        // 验证邮箱验证码
        if (isNullOrEmpty(loginByEmail.getCode())) {
            return R.fail("验证码不能为空");
        }

        boolean isVerified = codeService.verify(loginByEmail.getEmail(), loginByEmail.getCode());
        if (!isVerified) {
            return R.fail("验证码无效或已过期");
        }
        System.out.println("验证通过: " + loginByEmail.getEmail());

        // 创建并返回令牌
        LoginUser loginUser = new LoginUser();
        HashSet<String> role = new HashSet<>();
        role.add("admin");
        loginUser.setRoles(role);
        HashSet<String > permission = new HashSet<>();
        permission.add("*:*:*");
        loginUser.setPermissions(permission);
//        System.out.println(loginUser);

        SysUser sysUser = new SysUser();
        sysUser.setUserId(1L);
        sysUser.setUserName("admin");
        sysUser.setPassword("admin123");
        loginUser.setSysUser(sysUser);
        Map<String, Object> token = tokenService.createToken(loginUser);

        if (token == null) {
            return R.fail("令牌生成失败");
        }
        System.out.println("生成的令牌: " + token);
        return R.ok(token,"验证成功");
    }

    // 工具方法：检查字符串是否为空
    private boolean isNullOrEmpty(String str) {
        return str == null || str.trim().isEmpty();
    }


}
